package com.heima.wemedia.service.impl;

import com.heima.wemedia.service.OCRService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.Tesseract;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.io.File;

@Slf4j
@Service
public class OCRServiceImpl implements OCRService {

    @Resource
    private Tesseract tesseract;

    @Override
    public String doOCR(BufferedImage image) {
        try {
            //执行ocr识别
            return postHandle(tesseract.doOCR(image));
        } catch (Exception e) {
            log.error("图片识别文字失败", e);
        }
        return null;
    }

    @Override
    public String doOCR(File imageFile) {
        try {
            //执行ocr识别
            return postHandle(tesseract.doOCR(imageFile));
        } catch (Exception e) {
            log.error("图片识别文字失败", e);
        }
        return null;
    }

    private String postHandle(String result) {
        //替换回车和tal键  使结果为一行
        return result.replaceAll("\\r|\\n", "-").replaceAll(" ", "");
    }
}
